package com.whq.knowverywell.business.http;

import org.json.JSONObject;

import android.content.Context;

import com.whq.knowverywell.business.LoginUtil;
import com.whq.knowverywell.business.model.StoreInfo;
import com.whq.knowverywell.util.LogUtil;
import com.whq.knowverywell.util.NetworkUtil;
import com.whq.knowverywell.util.StringUtil;
import com.whq.knowverywell.util.constant.CfgConstant;
import com.whq.knowverywell.util.httpclient.HttpClientUtil;
import com.whq.knowverywell.util.httpclient.HttpResult;

/**
 * 获取单个门店的销售统计数据
 * @author wanghuaiqiang
 *
 */
public class GetOneStoreInfoUtil {
	private static final String TAG = "GetOneStoreInfoUtil";
	
	public static StoreInfo getInfo(Context context, String storeCode) {
		StoreInfo retObj = new StoreInfo();
		if (context == null) {
			return retObj;
		}
		if (!NetworkUtil.isNetworkAvailable(context)) {
			return retObj;
		}
		
		String token = LoginUtil.getLoginToken(context);
		if (StringUtil.isBlank(token)) {
			return retObj;
		}
		
		// 获取guid
		String path = CfgConstant.SERVER_CONTEXT + "/store/oneStoreInfo";
		StringBuilder sb = new StringBuilder();
		sb.append("token=" + token);
		sb.append("&storeCode=" + storeCode);
		sb.append("&version=" + CfgConstant.SERVER_API_VERSION);
		sb.append("&source=" + CfgConstant.SERVER_API_SOURCE);
		
		String req = sb.toString();
		HttpResult httpResult = HttpClientUtil.callServer(context, CfgConstant.SERVER_HOST, false, path, req, "UTF-8");
		if ( (httpResult == null) 
				|| (!httpResult.checkCode()) 
				) {
			return retObj;
		}
		
		String responseStr = httpResult.getResp();
		if (StringUtil.isBlank(responseStr)) {
			return retObj;
		}
		
		try {
			JSONObject recordJson = new JSONObject(responseStr);
			int resultCode = recordJson.optInt("resultCode", -1);
			if (resultCode != 0) {
				ChkResponseUtil.chkLogoutErrorCode(context, resultCode);
				return retObj;
			}
			
			if (recordJson.isNull("data")) {
				return retObj;
			}
			
			JSONObject dataJson = recordJson.getJSONObject("data");
			
			retObj.setAddress(dataJson.optString("Address", ""));
			retObj.setContact(dataJson.optString("Contact", ""));
			retObj.setMobile(dataJson.optString("Mobile", ""));
			retObj.setStoreCode(dataJson.optString("StoreCode", ""));
			retObj.setStoreName(dataJson.optString("StoreName", ""));
			retObj.setStoreNameFirstPYLetter(dataJson.optString("StoreNameFirstPYLetter", ""));
			retObj.setTel(dataJson.optString("Tel", ""));
				
		} catch (Exception e) {
			LogUtil.e(TAG, "解析json串出错：", e);
		}
		return retObj;
	}
	
}
